package com.sunyy.codegenerator.config.freemarker;

import cn.hutool.extra.spring.SpringUtil;
import com.sunyy.codegenerator.common.MyException;
import com.sunyy.codegenerator.service.CosService;
import freemarker.cache.ByteArrayTemplateLoader;
import lombok.extern.slf4j.Slf4j;

/**
 * @author sunyy
 * @since 2025/7/20
 */
@Slf4j
public class MyByteArrayTemplateLoader extends ByteArrayTemplateLoader {
    private final Object lock = new Object();

    @Override
    public Object findTemplateSource(String name) {
        Object templateSource = super.findTemplateSource(name);
        if (templateSource == null) {
            synchronized (lock) {
                templateSource = super.findTemplateSource(name);
                if (templateSource == null) {
                    // 从对象存储中获取
                    CosService bean = SpringUtil.getBean(CosService.class);
                    byte[] fileBytes;
                    try {
                        fileBytes = bean.getFileBytes("code-generator", name);
                    } catch (MyException e) {
                        log.error("{} 文件为找到!!", name);
                        fileBytes = null;
                    }
                    if (fileBytes == null || fileBytes.length == 0) {
                        return null;
                    }
                    putTemplate(name, fileBytes);
                    templateSource = super.findTemplateSource(name);
                }
            }
        }
        return templateSource;
    }
}
